import { postMyChangemobile, postMySendchangemobilecode } from "@/api/siderBar/my"
import { message } from "ant-design-vue"

type FormState = {
    mobile?: string
    code?: string
}
export function useBindPhone(fn?: IFn) {
    const { state: showMobile, on: openMobile, off: closeMobile } = useSwitch(false)
    const {
        clearValidate,
        formLoading,
        formRef,
        formState,
        rules,
        handleFormSubmit,
        resetFormState
    } = useFormState<FormState>({
        getInitialState() {
            return {}
        },
        rules: {
            mobile: [
                { required: true, message: '请输入新手机号' },
                { pattern: /^(?:(?:\+|00)86)?1\d{10}$/, message: '手机号格式有误' }
            ],
            code: [
                { required: true, message: '请输入验证码' }
            ]
        }
    })
    useEffectScope(() => {
        watch(showMobile, () => {
            if (showMobile.value === false) {
                clearValidate()
                resetFormState()
            }
        })
    })
    const { remain, reset, running, triggerSend } = useVerifyCode(60, () => formState.value.mobile!, mobile => postMySendchangemobilecode({ mobile }))
    async function handleSubmit() {
        try {
            // @ts-ignore
            await handleFormSubmit(postMyChangemobile)
            closeMobile()
            message.success("手机号修改成功")
            fn?.()
        } catch (error) {
            reset()
        }
    }
    return {
        formLoading,
        formState,
        rules,
        showMobile,
        openMobile,
        handleSubmit,
        formRef,
        remain, 
        running, 
        triggerSend
    }
}